﻿using System;
using AspNetInfo.Diagnostics;

namespace AspNetInfo.SampleDiagnosticPlugIn
{
    public class ConfigPermissionTest : ITest
    {
        public ConfigPermissionTest()
        {
            Result = new TestResult { Status = TestStatus.New };
        }
        public string Name
        {
            get { return "WebConfigPermissions"; }
        }

        public string Description
        {
            get { return "Can read and write to ~/web.config"; }
        }

        public TestResult Result
        {
            get;
            private set;
        }

        public TestResult Execute()
        {
            try
            {
                var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

                if (config.HasFile)
                {
                    if (config.AppSettings.Settings["AspNetInfo.TestPassed"] == null)
                        config.AppSettings.Settings.Add("AspNetInfo.TestPassed", DateTime.Now.ToLongDateString());
                    else
                        config.AppSettings.Settings["AspNetInfo.TestPassed"].Value = DateTime.Now.ToLongDateString();
                    config.Save();

                    // Cleanup temporary setting used to test write permission.
                    config.AppSettings.Settings.Remove("AspNetInfo.TestPassed");
                    config.Save();
                }
                else
                {
                    Result.Status = TestStatus.Failed;
                    Result.Messages.Add(config.FilePath + " is missing.");
                }

                Result.Status = TestStatus.Passed;
            }
            catch (Exception exc)
            {
                Result.Status = TestStatus.Failed;
                Result.Messages.Add(exc.Message);
                Result.Error = exc;
            }

            return Result;
        }
    }
}
